package com.example.coffeeseller_2.views.fragments.yagai_zhuanbei;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.ChooseCoffeeInfo;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.MachineConfig;
import com.example.coffeeseller_2.model.communicate.TaskService;
import com.example.coffeeseller_2.model.contentprovider.ApplicationConstance;
import com.example.coffeeseller_2.model.contentprovider.SharedPreferencesManager;
import com.example.coffeeseller_2.model.contentprovider.SingleMaterialList;
import com.example.coffeeseller_2.model.factory.FragmentEnum;
import com.example.coffeeseller_2.model.helper.CheckCurMachineState;
import com.example.coffeeseller_2.model.helper.TradeAnimManager;
import com.example.coffeeseller_2.model.helper.view_helper.LanguageSwitchHelper;
import com.example.coffeeseller_2.model.listenner.MessageReceviedListener;
import com.example.coffeeseller_2.model.listenner.OnCoffeeChildClickListenner;
import com.example.coffeeseller_2.model.listenner.OnIsCanMakingListener;
import com.example.coffeeseller_2.model.listenner.OnRecycleTouchListenner;
import com.example.coffeeseller_2.model.model.GetFormula;
import com.example.coffeeseller_2.utils.JinzhiSwitcher;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.SecondToDate;
import com.example.coffeeseller_2.views.HomeActivity;
import com.example.coffeeseller_2.views.fragments.BasicFragment;
import com.example.coffeeseller_2.widget.MyBeiSaiErView;
import com.example.coffeeseller_2.widget.RecyclerViewBanner;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cof.ac.inter.CoffMsger;
import cof.ac.inter.DebugAction;
import cof.ac.inter.MachineState;
import cof.ac.inter.Result;

/**
 * Created by WH on 2018/7/27.
 * 选杯界面
 * 压盖
 */

public class ChooseCupFragment extends BasicFragment implements View.OnClickListener
        , OnCoffeeChildClickListenner, OnIsCanMakingListener, MessageReceviedListener, OnRecycleTouchListenner {
    private static final String TAG = "ChooseCupFragment";
    private View mContent;
    private HomeActivity mHomeActivity;
    /*header view*/
    private LinearLayout mHeader;
    private TextView mLanguage_chinese, mLanguage_english, mContact_phone, mTimeOfClear;
    private ImageView mNetState;
    /*content view*/
    private LinearLayout mContentContainner;
    private LinearLayout mLeftLayout;
    private LinearLayout mRightLayout;
    private LinearLayout mOpenDoor;
    private RecyclerViewBanner mRecyclerViewBanner;

    private ImageView loading_1;
    private ImageView loading_2;
    private ImageView loading_3;
    private ImageView loading_4;

    private MyBeiSaiErView myBeiSaiErView;

    private RelativeLayout mStopToSellLayout;
    private TextView mErrCode;
    /*private TextView mCenterManager;
    private int netType = -1;*/

    private Handler handler;
    private Timer machineStateCheckTimer;
    private TimerTask machineStateCheckTimerTask;
    private boolean isSelling = true;
    private boolean isAllCoffeeSaleOver = false;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    /*    if (mContent == null) {
            mContent = inflater.inflate(R.layout.fragment_buy, null, false);
            initViews();
        }
        ViewGroup parent = (ViewGroup) mContent.getParent();
        if (parent != null) {
            parent.removeView(mContent);
        }*/
        mContent = inflater.inflate(R.layout.fragment_buy, null, false);
        initViews();
        initData();

        return mContent;
    }

    private void initViews() {
        /*header*/
        mLanguage_chinese = (TextView) mContent.findViewById(R.id.language_chinese);
        mLanguage_english = (TextView) mContent.findViewById(R.id.language_english);
        mNetState = (ImageView) mContent.findViewById(R.id.netState);
        mContact_phone = (TextView) mContent.findViewById(R.id.contact_phone);
        TextView mQubeima = (TextView) mContent.findViewById(R.id.qubeima);
        mLanguage_chinese.setOnClickListener(this);
        mLanguage_english.setOnClickListener(this);
        mQubeima.setOnClickListener(this);
        mNetState.setOnClickListener(this);
        /*content*/
        mLeftLayout = (LinearLayout) mContent.findViewById(R.id.contentLeftLayout);
        mRightLayout = (LinearLayout) mContent.findViewById(R.id.contentRightLayout);
        mRecyclerViewBanner = (RecyclerViewBanner) mContent.findViewById(R.id.recyclerViewBanner);
        mLeftLayout.setOnClickListener(this);
        mRightLayout.setOnClickListener(this);

        mHeader = (LinearLayout) mContent.findViewById(R.id.header);
        mContentContainner = (LinearLayout) mContent.findViewById(R.id.content);
        mStopToSellLayout = (RelativeLayout) mContent.findViewById(R.id.stopToSell);
        mErrCode = (TextView) mContent.findViewById(R.id.errCode);
        TextView mCenterManager = (TextView) mContent.findViewById(R.id.centerManager);

        mCenterManager.setOnClickListener(this);

       // mTimeOfClear = (TextView) mContent.findViewById(R.id.lastClearTime);

        myBeiSaiErView = (MyBeiSaiErView) mContent.findViewById(R.id.myBeiSaiErView);

        loading_1 = (ImageView) mContent.findViewById(R.id.loading_1);
        loading_2 = (ImageView) mContent.findViewById(R.id.loading_2);
        loading_3 = (ImageView) mContent.findViewById(R.id.loading_3);
        loading_4 = (ImageView) mContent.findViewById(R.id.loading_4);
        mOpenDoor = (LinearLayout) mContent.findViewById(R.id.openDoor);
        mOpenDoor.setOnClickListener(this);
        if (mOpenDoor.getVisibility() != View.GONE) {
            mOpenDoor.setVisibility(View.GONE);
        }
        mStopToSellLayout.setVisibility(View.GONE);
        mLanguage_english.setVisibility(View.INVISIBLE);


    }

    private void initData() {
        mHomeActivity = (HomeActivity) getActivity();
        mHomeActivity.showFooter(true);
        mRecyclerViewBanner.setOnChildClickListenner(this);
        mRecyclerViewBanner.setRvBannerData(SingleMaterialList.getInstance(mHomeActivity).getLastCoffeeList());
//        update();
        mRecyclerViewBanner.setOnTouchListenner(this);
        TaskService.getInstance().setOnMessageReceviedListener(this);
        switchLanguage(true);
//        setClearTime();
        mContact_phone.setText(MachineConfig.getPhone());
        mErrCode.setText(MachineConfig.getPhone());
        mHomeActivity.setOnIsCanMakingListener(this);
        handler = new Handler();
//        netType = -1;
        isSelling = true;
        setNetType();
        startMachineCheckTimer();
    }

    private void setClearTime() {
        if (SharedPreferencesManager.getInstance(mHomeActivity).getLastCleanningTime() <= 0) {

            mTimeOfClear.setText(SecondToDate.getDateToString(ApplicationConstance.getInstance().getLastClearMachineTime()) + "");
        } else {
            mTimeOfClear.setText(SecondToDate.getDateToString(
                    SharedPreferencesManager.getInstance(mHomeActivity).getLastCleanningTime()) + "");
        }
        ApplicationConstance.getInstance().setClearTimeSeted(true);
    }

    private boolean isCheckShiftNotRightPlace = false;//杯架在初始位置
    private long firstCheckShiftNotRightPlace;

    private void startMachineCheckTimer() {


        if (machineStateCheckTimer != null || machineStateCheckTimerTask != null) {
            return;
        }

        Log.d(TAG, "startMachineCheckTimer");

        if (machineStateCheckTimer == null) {
            machineStateCheckTimer = new Timer();
            machineStateCheckTimerTask = new TimerTask() {
                @Override
                public void run() {
/*
                    *//*
                    * 修改清洗记录
                    * *//*
                    if (!ApplicationConstance.getInstance().isClearTimeSeted()) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                setClearTime();
                            }
                        });
                    }*/

                    if (ApplicationConstance.getInstance().isHasCoffeeSelected()) {
                        return;
                    }

                    /*
                    * 如果所有咖啡都售罄了
                    * */
                    if (isAllCoffeeSaleOver) {

                        if (isSelling) {

                            switchPage(true, "等待工作人员补充原料");
                        }
                        return;
                    }

                    setNetType();
                    MachineState machineState = CheckCurMachineState.getInstance().getMachineState();
                    if (machineState.getResult().getCode() != Result.SUCCESS) {
                        Log.d(TAG, "result.code= " + machineState.getResult().getCode());
                        isSwitchPage(false, "通信失败");
                        return;

                    }

                       /*
                    * 如果检测到咖啡豆不足了，显示售罄
                    * */
                    if (machineState.isBeanEnough() && ApplicationConstance.getInstance().isBeanEnough()) {

                    } else if (machineState.isBeanEnough() && !ApplicationConstance.getInstance().isBeanEnough()) {

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                update();
                                MyLog.W(TAG, "咖啡豆 由缺少变为充足");
                            }
                        });

                    } else if (!machineState.isBeanEnough() && ApplicationConstance.getInstance().isBeanEnough()) {

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                update();
                                MyLog.W(TAG, "咖啡豆 由充足变为缺少");
                            }
                        });
                    } else if (!machineState.isBeanEnough() && !ApplicationConstance.getInstance().isBeanEnough()) {

                    }

                    boolean isShelfRightPlace = true;
                    if (!machineState.isCupShelfRightPlace() && !isCheckShiftNotRightPlace) {
                        firstCheckShiftNotRightPlace = System.currentTimeMillis();
                        isCheckShiftNotRightPlace = true;

                    } else if (machineState.isCupShelfRightPlace()) {
                        isCheckShiftNotRightPlace = false;
                    }

                    if (System.currentTimeMillis() - firstCheckShiftNotRightPlace > 30 * 1000 && isCheckShiftNotRightPlace) {
                        isShelfRightPlace = false;
                    }
 /*                   //门关且有杯（针对自动门，带杯架，非压盖）
                    boolean hasCupAndDoorClosed = machineState.hasCupOnShelf() && machineState.isLittleDoorOpen();
                    boolean canMaking = CheckCurMachineState.getInstance()
                            .isCanMaking(machineState) && isShelfRightPlace && !hasCupAndDoorClosed;
                    String errCode = JinzhiSwitcher.byte2Hex(machineState.getMajorState().getHighErr_byte())
                         //  +" | "+machineState.getWarnCode()//警告码
                         //   +" | "+machineState.getWarnDesCode()//二级码
                            + (isShelfRightPlace ? "" : " | 杯架故障")
                            + (!machineState.isFrontDoorOpen() ? "" : " | 机器维护中")
                            + (!hasCupAndDoorClosed ? "" :" | 有杯子未取走");*/

                    //只判断有杯（针对手动门，带杯架，非压盖）
                /*    boolean hasCupOnShelf = machineState.hasCupOnShelf();
                    boolean canMaking = CheckCurMachineState.getInstance()
                            .isCanMaking(machineState) && isShelfRightPlace && !hasCupOnShelf;

                    final String errCode = JinzhiSwitcher.byte2Hex(machineState.getMajorState().getHighErr_byte())
                            //  +" | "+machineState.getWarnCode()//警告码
                            //   +" | "+machineState.getWarnDesCode()//二级码
                            + (isShelfRightPlace ? "" : " | 杯架故障")
                            + (!machineState.isFrontDoorOpen() ? "" : " | 机器维护中")
                            + (!hasCupOnShelf ? "" : " | 有杯子未取走");*/

                    //针对自动门，压盖
                    boolean hasCupOnShelf = machineState.hasCupOnShelf();
                    //废液盘是否在正确在接废液位置，false表示可以制作咖啡
                    boolean isWasteLiquidInRightPlace = machineState.isWasteLiquidInRightPlace();
                    boolean canMaking = CheckCurMachineState.getInstance()
                            .isCanMaking(machineState) && !hasCupOnShelf;


                    if (!hasCupOnShelf) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mOpenDoor.getVisibility() != View.GONE) {
                                    mOpenDoor.setVisibility(View.GONE);
                                }
                            }
                        });
                    } else {

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mOpenDoor.getVisibility() != View.VISIBLE) {
                                    mOpenDoor.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }


                    final String errCode = JinzhiSwitcher.byte2Hex(machineState.getMajorState().getHighErr_byte())
                            // +" | "+machineState.getWarnCode()//警告码
                            // +" | "+machineState.getWarnDesCode()//二级码
                            // +(!isWasteLiquidInRightPlace?"":" | 废液盘故障")
                            + (!machineState.isFrontDoorOpen() ? "" : " | 机器维护中")
                            + (!hasCupOnShelf ? "" : " | 有杯子未取走");

                    isSwitchPage(canMaking, errCode);


                }

            };
        }
        machineStateCheckTimer.schedule(machineStateCheckTimerTask, 0, 2000);//5 * 1000
    }

    private void isSwitchPage(boolean canMaking, final String errCode) {
        if (canMaking && isSelling) {//如果已经是售卖状态了
            Log.d(TAG, "selling aways");
        } else if (!canMaking && !isSelling) {//如果已经是停止售卖状态
            Log.d(TAG, "stopToSell aways");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    mErrCode.setText(errCode);
                }
            });
        } else {

            Log.d(TAG, "change state : stopToSell = " + !canMaking);
            isSelling = canMaking;
            switchPage(!canMaking, errCode);
        }
    }

    private void switchLanguage(boolean ischineseSelected) {
        if (ischineseSelected) {

            mLanguage_chinese.setSelected(ischineseSelected);
            mLanguage_english.setSelected(!ischineseSelected);
            LanguageSwitchHelper.switchLanguage(mHomeActivity, "zh");
        } else {
            mLanguage_english.setSelected(!ischineseSelected);
            mLanguage_chinese.setSelected(ischineseSelected);
            LanguageSwitchHelper.switchLanguage(mHomeActivity, "en");
        }


    }

    public void update() {
        isAllCoffeeSaleOver = false;
        List<Coffee> coffees = SingleMaterialList.getInstance(mHomeActivity).getCoffeeList();
        mRecyclerViewBanner.setRvBannerData(coffees);
        if (isAllCoffeeSaleOver(coffees)) {
            isAllCoffeeSaleOver = true;
        }

    }

    private boolean isAllCoffeeSaleOver(List<Coffee> coffees) {
        boolean isAllCoffeeSaleOver = true;
        for (int i = 0; i < coffees.size(); i++) {
            Coffee coffee = coffees.get(i);
            if (!coffee.isOver()) {
                isAllCoffeeSaleOver = false;
            }
        }
        return isAllCoffeeSaleOver;
    }

    public void setRecyclerViewVisiable(boolean isVisiable) {
        mRecyclerViewBanner.setVisiable(isVisiable);
//        mRecyclerViewBanner.setIsPlay(isClose);
    }

    /*
    * stopToSell:true表示机器存在故障
    * */
    private void switchPage(final boolean stopToSell, final String errCode) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "switchPage stopToSell= " + stopToSell);
                if (stopToSell) {
                    mStopToSellLayout.setVisibility(View.VISIBLE);
                    mHeader.setVisibility(View.GONE);
                    mContentContainner.setVisibility(View.GONE);
                    mErrCode.setText(errCode);
                    setRecyclerViewVisiable(false);
                    startAnim();

                    MyLog.W(TAG, "stop to sell err: " + errCode);
                } else {
                    mStopToSellLayout.setVisibility(View.GONE);
                    mHeader.setVisibility(View.VISIBLE);
                    mContentContainner.setVisibility(View.VISIBLE);
                    setRecyclerViewVisiable(true);
                    clearAnim();
                }

            }
        });

    }

    int count = 0;

    private void startAnim() {
        if (loading_1 == null && loading_2 == null && loading_3 == null && loading_4 == null) {
            return;
        }
        TradeAnimManager.startWaitRotateAnim(loading_1, 0, 360);
        TradeAnimManager.startWaitRotateAnim(loading_2, 0, 360);
        TradeAnimManager.startWaitRotateAnim(loading_3, 0, 360);
        TradeAnimManager.startWaitRotateAnim(loading_4, 0, -360);
    }

    private void clearAnim() {

        if (loading_1 != null) loading_1.clearAnimation();
        if (loading_2 != null) loading_2.clearAnimation();
        if (loading_3 != null) loading_3.clearAnimation();
        if (loading_4 != null) loading_4.clearAnimation();
        count = 0;
    }

    private void setNetType() {
        boolean hasNet = mHomeActivity.checkNetWorkType();
    /*    if (netType == MachineConfig.getNetworkType()) {
            return;
        } else {
            netType = MachineConfig.getNetworkType();
        }*/
        switch (MachineConfig.getNetworkType()) {
            case 0://离线
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mNetState.setImageResource(R.mipmap.offline);

                    }
                });
                break;
            case 1://移动网
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mNetState.setImageResource(R.mipmap.net_4g);

                    }
                });
                break;

            case 2://WiFi
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mNetState.setImageResource(R.mipmap.wifi);

                    }
                });
                break;
        }
    }

    public void setWaveOpen(boolean isStop) {
        myBeiSaiErView.setStop(isStop);
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.centerManager:

                mHomeActivity.replaceFragment(FragmentEnum.ChooseCupNumFragment, FragmentEnum.LoginFragment);

                break;
            case R.id.language_chinese:
                switchLanguage(true);

                break;
            case R.id.language_english:
                switchLanguage(false);
                break;
            case R.id.qubeima:

                //跳转到取杯码fragment，

                mHomeActivity.replaceFragment(FragmentEnum.ChooseCupNumFragment, FragmentEnum.QubeimaTasteFragment);
                break;

            case R.id.netState:
                mHomeActivity.replaceFragment(FragmentEnum.ChooseCupNumFragment, FragmentEnum.LoginFragment);

                break;
            case R.id.contentLeftLayout:
                Log.d(TAG, "on leftLayout clicked");
                mRecyclerViewBanner.showPrevious();
                break;
            case R.id.contentRightLayout:
                mRecyclerViewBanner.showNext();
                break;
            case R.id.openDoor:
                Result result = CoffMsger.getInstance().Debug(DebugAction.CTR_LITTLEDOOR, 0, 1);
                if (result.getCode() == Result.SUCCESS) {
                    Toast.makeText(getActivity(), "开门成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "关门失败,错误 " + result.getErrDes(), Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onClick(ChooseCoffeeInfo coffeeInfo) {
        Log.d(TAG, "onClick ");
        if (coffeeInfo == null) {
            Log.d(TAG, "coffeeInfo == null");
            return;
        }
        ApplicationConstance.getInstance().setHasCoffeeSelected(true);
        mHomeActivity.addTastPayFrag(coffeeInfo);

    }

    @Override
    public void onAnimEnd() {
        Log.d(TAG, "onAnimEnd ");
        mHomeActivity.showTastPayFrag();
    }

    @Override
    public void getMsgType(String msgType) {
        MyLog.d(TAG, "getMsgType come!");

        MyLog.W(TAG, "mqtt Formula changed : \n " + msgType);

        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                GetFormula getFormula = new GetFormula();
                Boolean isUpdate = getFormula.getFormula(mHomeActivity);
                return isUpdate;
            }

            @Override
            protected void onPostExecute(Boolean isUpdate) {
                super.onPostExecute(isUpdate);
                if (isUpdate) {
                    update();
                }

            }
        }.execute();
    }

    @Override
    public void stopSomeOneCoffeeSell(int formulaID) {

    }

    @Override
    public void notifyDataSetChange() {

    }

    @Override
    public void StateArrived(final boolean canMaking, final String errCode) {

    }

    @Override
    public void onTouched(final boolean isTouched) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (isTouched) {
                    mLeftLayout.setVisibility(View.GONE);
                    mRightLayout.setVisibility(View.GONE);
                } else {
                    mLeftLayout.setVisibility(View.VISIBLE);
                    mRightLayout.setVisibility(View.VISIBLE);
                }
            }
        });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (machineStateCheckTimer != null) {
            machineStateCheckTimer = null;
        }
        if (machineStateCheckTimerTask != null) {
            machineStateCheckTimerTask.cancel();
            machineStateCheckTimerTask = null;
        }
    }
}
